package JavaEE_notes.common_API.Network;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author TaiZai
 * @data 2024/9/26 14:04
 */
public class ServerReaderThread extends Thread {
    private Socket socket;
    public ServerReaderThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            while (true) {
                try {
                    String msg = dis.readUTF();
                    System.out.println(msg + "来自" + socket.getRemoteSocketAddress());
                    // 把消息分发给全部客户端进行接收
                    sendMsgToAll(msg);
                } catch (Exception e) {
                    System.out.println("有人下线了：" + socket.getRemoteSocketAddress());
                    TCP_Server_Thread.onLineSockets.remove(socket);
                    dis.close();
                    socket.close();
                    break;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void sendMsgToAll(String msg) throws IOException {
        // 发送给全部在线的socket管道接收
        for (Socket onLineSocket : TCP_Server_Thread.onLineSockets) {
            OutputStream os = onLineSocket.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(msg);
            dos.flush();
        }
    }
}
